package com.atguigu.flink0624.chapter07.state;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.FunctionInitializationContext;
import org.apache.flink.runtime.state.FunctionSnapshotContext;
import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.ArrayList;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/15 14:22
 */
public class Flink01_Operator_State_ListSate {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        env.enableCheckpointing(3000);  // 开启checkpoint, 周期是3000ms. 默认checkpoint的地址: JobManager的内存
        
        env
            .socketTextStream("hadoop162", 9999)
            .flatMap(new MyFlatMap())
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static class MyFlatMap implements FlatMapFunction<String, String>, CheckpointedFunction {
        
        ArrayList<String> words = new ArrayList<>();
        private ListState<String> listState;
    
        @Override
        public void flatMap(String value,
                            Collector<String> out) throws Exception {
            String[] data = value.split(" ");
            for (String word : data) {
                words.add(word);
            }
            
            out.collect(words.toString());
    
            if (value.contains("x")) {
                throw new RuntimeException("手动抛出异常");
            }
        }
        
        // 把状态保存起来
        // 每个并行度都会周期性的执行, 把数据周期性的保存到状态中
        @Override
        public void snapshotState(FunctionSnapshotContext ctx) throws Exception {
//            System.out.println("MyFlatMap.snapshotState");
            // 向状态中存入集合中的数据
//            listState.addAll(words);
            listState.update(words);  // 是先删除, 再新增
        }
        
        // 初始状态: 当程序恢复的时候, 从状态中读取数据恢复
        // 程序启动的时候, 每个并行度执行一次
        @Override
        public void initializeState(FunctionInitializationContext ctx) throws Exception {
            System.out.println("MyFlatMap.initializeState");
            // alt+ctrl+f
            listState = ctx.getOperatorStateStore().getListState(new ListStateDescriptor<String>("list", String.class));
    
            Iterable<String> it = listState.get();
            for (String s : it) {
                words.add(s);
            }
        }
    }
}
